package com.webinsky.service.resource.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.webinsky.common.proj.DelFlag;
import com.webinsky.common.proj.Lang;
import com.webinsky.common.utils.db.PageOrder;
import com.webinsky.domain.resource.ResOrders;
import com.webinsky.domain.resource.ResType;
import com.webinsky.domain.resource.Resource;
import com.webinsky.domain.resource.Resources;
import com.webinsky.persist.dao.resource.ImageMapper;
import com.webinsky.persist.dao.resource.VideoMapper;
import com.webinsky.persist.entity.resource.Image;
import com.webinsky.persist.entity.resource.ImageFilter;
import com.webinsky.persist.entity.resource.Video;
import com.webinsky.persist.entity.resource.VideoFilter;
import com.webinsky.service.resource.ResManagement;

@Service
public class ResManagementImpl implements ResManagement {
	private static final Logger logger = LoggerFactory.getLogger(ResManagementImpl.class);
	@Autowired
	private ImageMapper imageDao;
	@Autowired
	private VideoMapper videoDao;
	
	private Video convertVideo(Resource res){
		Video video = new Video();
		video.setLanguage(res.getLanguage().getLang());
		video.setName(res.getName());
		video.setSiteId(res.getSiteId());
		video.setFile_name(res.getFileName());
		return video;
	}
	
	private Image convertImage(Resource res){
		Image image = new Image();
		image.setLanguage(res.getLanguage().getLang());
		image.setSiteId(res.getSiteId());
		image.setName(res.getName());
		image.setFile_name(res.getFileName());
		return image;
	}
	
	private Resource convertVideo(Video video){
		Resource resource = new Resource();
		resource.setFileName(video.getFile_name());
		resource.setLanguage(Lang.parse(video.getLanguage()));
		resource.setSiteId(video.getSiteId());
		resource.setName(video.getName());
		resource.setFileName(video.getFile_name());
		resource.setType(ResType.Video);
		resource.setUid(video.getId().toString());
		resource.setCreated(video.getCreate_at());
		return resource;
	}
	
	private Resource convertImage(Image image){
		Resource resource = new Resource();
		resource.setFileName(image.getFile_name());
		resource.setLanguage(Lang.parse(image.getLanguage()));
		resource.setSiteId(image.getSiteId());
		resource.setName(image.getName());
		resource.setFileName(image.getFile_name());
		resource.setType(ResType.Image);
		resource.setUid(image.getId().toString());
		resource.setCreated(image.getCreate_at());
		return resource;
	}
	
	@Override
	public void createRes(Resource res) {
		if ( res != null ){
			switch ( res.getType() ){
			case Image: {
				List<Image> images = imageDao.selectBySiteIdNameAndLangDel(res.getSiteId(), res.getName(), res.getLanguage().getLang(), DelFlag.UNDel.getFlag());
				Image image = null;
				if ( !images.isEmpty() ){
					image = images.get(0);
					image.setFile_name(res.getFileName());
					image.setName(res.getName());
					image.setUpdate_at(new Date());
					imageDao.updateByPrimaryKey(image);
					res.setUid(image.getId().toString());
				} else {
					image = convertImage(res);
					image.setDel(DelFlag.UNDel.getFlag());
					imageDao.insert(image);
					res.setUid(image.getId().toString());
				}
				break;
			}
			case Video: {
				List<Video> videos = videoDao.selectBySiteIdNameAndLangDel(res.getSiteId(), res.getName(), res.getLanguage().getLang(), DelFlag.UNDel.getFlag());
				Video video = null;
				if ( !videos.isEmpty() ){
					video = videos.get(0);
					video.setFile_name(res.getFileName());
					video.setName(res.getName());
					video.setUpdate_at(new Date());
					videoDao.updateByPrimaryKey(video);
				} else {
					video = convertVideo(res);
					video.setDel(DelFlag.UNDel.getFlag());
					videoDao.insert(video);
					res.setUid(video.getId().toString());
				}
				break;
			}
			default:
				logger.info("[createRes] default");
			}
			return;
		}
		logger.info("[createRes] 資源=null");
	}

	@Override
	public void delRes(String uid, ResType type) {
		if ( uid != null && type != null ){
			switch ( type ){
			case Image:
				Image image = imageDao.selectByPrimaryKey(Integer.valueOf(uid));
				if ( image != null && image.getDel().intValue() == 0 ){
					image.setDel(1);
					imageDao.updateByPrimaryKey(image);
				}
				break;
			case Video:
				Video video = videoDao.selectByPrimaryKey(Integer.valueOf(uid));
				if ( video != null && video.getDel().intValue() == 0 ){
					video.setDel(1);
					videoDao.updateByPrimaryKey(video);
				}
				break;
			default:
			}
			return;
		}
		logger.info("[delRes] uid=null");
	}

	@Override
	public List<Resource> getResourceByType(ResType type, int siteId, Lang lang) {
		List<Resource> resource = new ArrayList<>();
		if ( type != null ){
			switch( type ){
			case Image:
				List<Image> images = imageDao.selectByLang(lang.getLang());
				images.forEach(e -> {
					if ( e.getDel().intValue() == 0 )
						resource.add(convertImage(e));
				});
				break;
			case Video:
				List<Video> videos = videoDao.selectByLang(lang.getLang());
				videos.forEach(e -> {
					if ( e.getDel().intValue() == 0 )
						resource.add(convertVideo(e));
				});
				break;
			default:
			}
		}
		return resource;
	}

	@Override
	public Resources getResourcesByName(Lang lang, int siteId, String name, ResType type, int pageStart, int pageSize, ResOrders orders) {
		if ( lang != null && siteId > 0 && name != null && type != null ){
			Resources resources = new Resources();
			switch ( type ){
			case Image: {
				ImageFilter filter = new ImageFilter();
				filter.setSiteId(siteId);
				filter.setLang(lang.getLang());
				filter.setName(name);
				filter.setPageSize(pageSize);
				filter.setPageStart(pageStart);
				if ( orders != null ){
					orders.getOrders().forEach( o -> {
						PageOrder pageOrder = new PageOrder();
						pageOrder.setFieldName(o.getField());
						pageOrder.setIsAscOrDes(o.isAscOrDesc());
						filter.getOrders().add(pageOrder);
					});
				}
				List<Image> images = imageDao.selectByPagnation(filter);
				int count = imageDao.selectCountByPagnation(filter);
				images.forEach(e -> resources.getResources().add(convertImage(e)));
				resources.setTotalCount(count);
				break;
			}
			case Video:{
				VideoFilter filter = new VideoFilter();
				filter.setSiteId(siteId);
				filter.setLang(lang.getLang());
				filter.setPageSize(pageSize);
				filter.setName(name);
				filter.setPageStart(pageStart);
				if ( orders != null ){
					orders.getOrders().forEach( o -> {
						PageOrder pageOrder = new PageOrder();
						pageOrder.setFieldName(o.getField());
						pageOrder.setIsAscOrDes(o.isAscOrDesc());
						filter.getOrders().add(pageOrder);
					});
				}
				List<Video> videos = videoDao.selectByPagnation(filter);
				int count = videoDao.selectCountByPagnation(filter);
				videos.forEach(e -> resources.getResources().add(convertVideo(e)));
				resources.setTotalCount(count);
				break;
			}
			default:
			}
			return resources;
		}
		return null;
	}

	@Override
	public Resources getResourcesByPagnation(ResType type, int siteId, Lang lang, int pageStart, int pageSize, ResOrders order) {
		if ( type != null && siteId > 0 && lang != null ){
			Resources resources = new Resources();
			switch ( type ){
			case Image: {
				ImageFilter filter = new ImageFilter();
				filter.setSiteId(siteId);
				filter.setLang(lang.getLang());
				filter.setPageSize(pageSize);
				filter.setPageStart(pageStart);
				if ( order != null ){
					order.getOrders().forEach( o -> {
						PageOrder pageOrder = new PageOrder();
						pageOrder.setFieldName(o.getField());
						pageOrder.setIsAscOrDes(o.isAscOrDesc());
						filter.getOrders().add(pageOrder);
					});
				}
				List<Image> images = imageDao.selectByPagnation(filter);
				int count = imageDao.selectCountByPagnation(filter);
				images.forEach(e -> resources.getResources().add(convertImage(e)));
				resources.setTotalCount(count);
				break;
			}
			case Video: {
				VideoFilter filter = new VideoFilter();
				filter.setSiteId(siteId);
				filter.setLang(lang.getLang());
				filter.setPageSize(pageSize);
				filter.setPageStart(pageStart);
				if ( order != null ){
					order.getOrders().forEach( o -> {
						PageOrder pageOrder = new PageOrder();
						pageOrder.setFieldName(o.getField());
						pageOrder.setIsAscOrDes(o.isAscOrDesc());
						filter.getOrders().add(pageOrder);
					});
				}
				List<Video> videos = videoDao.selectByPagnation(filter);
				int count = videoDao.selectCountByPagnation(filter);
				videos.forEach(e -> resources.getResources().add(convertVideo(e)));
				resources.setTotalCount(count);
				break;
			}
			default:
				
			}
			return resources;
		}
		return null;
	}

	@Override
	public List<Resource> getImageResourceByIds(List<Integer> ids) {
		List<Resource> result = new ArrayList<>();
		if ( ids != null && !ids.isEmpty() ){
			List<Image> images = imageDao.selectByIds(ids);
			images.forEach(e -> result.add(convertImage(e)));
		}
		return result;
	}

	@Override
	public List<Resource> getVideoResourceByIds(List<Integer> ids) {
		List<Resource> result = new ArrayList<>();
		if ( ids != null && !ids.isEmpty() ){
			List<Video> videos = videoDao.selectByIds(ids);
			videos.forEach(e -> result.add(convertVideo(e)));
		}
		return result;
	}
	
	@Override
	public List<Resource> getVideoResourceByNames(List<String> names, int siteId, Lang lang){
		List<Resource> result = new ArrayList<>();
		if ( names != null && siteId > 0 && lang != null ) {
			List<Video> videos = videoDao.selectByNames(names, siteId, lang.getLang());
			videos.forEach(e -> {
				if ( e.getDel() == DelFlag.UNDel.getFlag() ){
					result.add(convertVideo(e));
				}
			});
		}
		return result;
	}
	

	@Override
	public boolean checkResourceName(int siteId, Lang lang, ResType type,
			String name) {
		if ( type == ResType.Image ){
			List<Image> images = imageDao.selectBySiteIdNameAndLangDel(siteId, name, lang.getLang(), DelFlag.UNDel.getFlag());
			return images.isEmpty() ? Boolean.FALSE : Boolean.TRUE;
		} else if ( type == ResType.Video ){
			List<Video> videos = videoDao.selectBySiteIdNameAndLangDel(siteId, name, lang.getLang(), DelFlag.UNDel.getFlag());
			return videos.isEmpty() ? Boolean.FALSE : Boolean.TRUE;
		}
		return false;
	}

	@Override
	public void resRename(ResType type, int resId, String newName) {
		if( type != null && newName != null && resId > 0 ){
			if ( type == ResType.Image ){
				Image image = imageDao.selectByPrimaryKey(resId);
				if ( image != null ){
					image.setFile_name(newName);
					image.setUpdate_at(new Date());
					imageDao.updateByPrimaryKey(image);
				}
			} else if ( type == ResType.Video ){
				Video video = videoDao.selectByPrimaryKey(resId);
				if ( video != null ){
					video.setFile_name(newName);
					video.setUpdate_at(new Date());
					videoDao.updateByPrimaryKey(video);
				}
			}
		}
	}

	@Override
	public int getCountByLang(Lang lang, ResType type) {
		if ( lang == null || type == null ){
			return -1;
		}
		int count = -1;
		switch ( type ){
		case Image:
			count = imageDao.selectCountByLang(lang.getLang());
			break;
		case Video:
			count = videoDao.selectCountByLang(lang.getLang());
			break;
		}
		return count;
	}

	@Override
	public List<Resource> getResourceByType(ResType type, int siteId) {
		List<Resource> resource = new ArrayList<>();
		if ( type != null && siteId > 0 ) {
			switch ( type ) {
			case Image:
				List<Image> imgs = imageDao.selectAcitveBySiteId(siteId, DelFlag.UNDel.getFlag());
				imgs.forEach(img -> resource.add(convertImage(img)));
				break;
			case Video:
				List<Video> videos = videoDao.selectActiveBySiteId(siteId, DelFlag.UNDel.getFlag());
				videos.forEach(video -> resource.add(convertVideo(video)));
				break;
			default:
			}
		}
		return resource;
	}

}
